
package com.tt.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.dialect.lock.UpdateLockingStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.tt.entity.ListImg;
import com.tt.entity.Page;
import com.tt.entity.Strategy;
import com.tt.entity.User;
import com.tt.service.StrategyServiceImpl;

@Controller
public class StrategyController {
	@Resource
	private StrategyServiceImpl serviceImpl;
	/**
	 * 发布旅行动态
	 * @param model
	 * @param strategy
	 * @param files
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="addstrategy", method=RequestMethod.POST,produces = "text/html; charset=utf-8")
	public Object addStrategy(Model model,Strategy strategy,@RequestParam("listimgs") MultipartFile[] files,HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		Set<String> listImgs=new HashSet<String>();
		//上传多张图片
		//先判断文件数组是否为空
		if(files!=null&&files.length>0){
			File path = new File(request.getServletContext().getRealPath("img"));
			if (!path.exists()) {// 检查该目录文件是否存在，不存在则创建目录
				path.mkdirs();
			}
			for(MultipartFile file:files){
				String filename = file.getOriginalFilename();//获取文件的名称
				if (filename!=null&&!filename.isEmpty()&&!filename.equals("")) {
					System.out.println("文件名："+filename);
					File imagesFile = new File(path, filename);
					if (!imagesFile.exists()) {// 检查该路径下的该文件是否已存在，不存在则创建新的空文件
						imagesFile.createNewFile();
					}
					file.transferTo(imagesFile);// 将文件复制到目标文件中
					listImgs.add(filename);
				}
			}
		}
		User user = (User) request.getSession().getAttribute("user");
		Integer uid = user.getId();
//		Integer uid = 2;
		boolean addStrtegy = serviceImpl.addStrtegy(strategy,uid,listImgs);
		PrintWriter out = response.getWriter();
		if (addStrtegy) {
			out.print("<script language='javascript'>alert('发布成功');window.location.href='strategylist'</script>");
			return out;
		}
		out.print("<script language='javascript'>alert('发布失败！');window.location.href='addstrategy.jsp'</script>");
		return out;
	}
	/**
	 * 查看所有动态
	 * @param request
	 * @return
	 */
	@RequestMapping(value="strategylist")
	public String findAllStrategy(HttpServletRequest request,Model model){
		int pageNum = Integer.parseInt(request.getParameter("pageNum")==null||request.getParameter("pageNum").equals("")?"1":request.getParameter("pageNum"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize")==null||request.getParameter("pageSize").equals("")?"8":request.getParameter("pageSize"));
		Page<Strategy> findAllStrategy = serviceImpl.findAllStrategy(pageNum,pageSize);
		model.addAttribute("findAllStrategy",findAllStrategy);
		return "/strategy.jsp";
	}
	/**
	 * 查看用户所发布的动态
	 * @param request
	 * @return
	 */
	@RequestMapping(value="finduserstrategy")
	public String findUserAllStrategy(HttpServletRequest request,Model model){
		User user = (User) request.getSession().getAttribute("user");
		Integer uid = user.getId();
//		Integer uid=2;
		int pageNum = Integer.parseInt(request.getParameter("pageNum")==null||request.getParameter("pageNum").equals("")?"1":request.getParameter("pageNum"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize")==null||request.getParameter("pageSize").equals("")?"8":request.getParameter("pageSize"));
		Page<Strategy> findUserAllStrategy = serviceImpl.findUserAllStrategy(uid,pageSize,pageNum);
		model.addAttribute("findUserAllStrategy", findUserAllStrategy);
		return "/mystrategy.jsp";
	}
	/**
	 * 查看动态详情
	 * @param request
	 * @return
	 */
	@RequestMapping(value="strategyinfo")
	public String strategyInfo(HttpServletRequest request,@RequestParam("id") Integer id,Model model){
		Strategy strategy = serviceImpl.findStraegyById(id);
		model.addAttribute("strategy", strategy);
		return "/strategyinfo.jsp";
	}
	/**
	 * 删除动态
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="deletestrategy",produces = "text/html; charset=utf-8")
	public Object deleteStrategy(HttpServletResponse response,@RequestParam("id") Integer id)throws IOException{
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		boolean deleteStrategy = serviceImpl.deleteStrategy(id);
		PrintWriter out = response.getWriter();
		if (deleteStrategy) {
			out.print("<script language='javascript'>alert('删除成功');window.location.href='finduserstrategy'</script>");
		}
		out.print("<script language='javascript'>alert('删除失败');window.location.href='finduserstrategy'</script>");
		return out;
	}
	/**
	 * 修改动态（先查询并回显该动态）
	 */
	@RequestMapping(value="toupdatestrategy")
	public String toUpdateStrategy(@RequestParam("id") Integer id,Model model){
		Strategy strategy = serviceImpl.findStraegyById(id);
		model.addAttribute("strategy", strategy);
		return "/updatestrategy.jsp";
	}
	/**
	 * 修改动态
	 * 获取传值并进行更新
	 */
	@RequestMapping(value="updatestrategy",method=RequestMethod.POST,produces = "text/html; charset=utf-8")
	public Object UpdateLockingStrategy(Strategy strategy,@RequestParam("listimgs") MultipartFile[] files,HttpServletRequest request,HttpServletResponse response)throws IOException{
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		User user = (User) request.getSession().getAttribute("user");
		PrintWriter out = response.getWriter();
		//获取原来的图片列表
		List<ListImg> listImgs = this.serviceImpl.findStrategyListImgById(strategy.getId());
		if(files!=null&&files.length>0){
			//如果上传的图片文件不为空，则删除原来的图片
			File path = new File(request.getServletContext().getRealPath("img"));
			if (!path.exists()) {// 检查该目录文件是否存在，不存在则创建目录
				path.mkdirs();
			}
			for(MultipartFile file:files){
				String filename = file.getOriginalFilename();//获取文件的名称
				if (filename!=null&&!filename.isEmpty()&&!filename.equals("")) {
					serviceImpl.deleteListImg(listImgs);
					listImgs.clear();
					System.out.println("文件名:"+filename);
					File imagesFile = new File(path, filename);
					if (!imagesFile.exists()) {// 检查该路径下的该文件是否已存在，不存在则创建新的空文件
						imagesFile.createNewFile();
					}
					file.transferTo(imagesFile);// 将文件复制到目标文件中
					ListImg lImg=new ListImg(filename);
					lImg.setStrategy(strategy);
					listImgs.add(lImg);
				}
			}
		}
		strategy.setUser(user);
		strategy.setListimg(listImgs);
		for(ListImg lImg:listImgs){
			System.out.println(lImg.getImg());
		}
		boolean updateStrategy = this.serviceImpl.updateStrategy(strategy);
		if (updateStrategy) {
			out.print("<script language='javascript'>alert('修改成功');window.location.href='finduserstrategy'</script>");
		}
		out.print("<script language='javascript'>alert('修改失败');window.location.href='finduserstrategy'</script>");
		return out;
		
	}
	/**
	 * 查询动态（模糊查询）
	 */
	@RequestMapping(value="searchstrategy")
	public String searchStrategy(@RequestParam("search") String search,Model model,HttpServletRequest request){
		int pageNum = Integer.parseInt(request.getParameter("pageNum")==null||request.getParameter("pageNum").equals("")?"1":request.getParameter("pageNum"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize")==null||request.getParameter("pageSize").equals("")?"8":request.getParameter("pageSize"));
		Page<Strategy> findAllStrategy = serviceImpl.searchStrategy(search,pageNum,pageSize);
		System.out.println(search);
		for(Strategy strategy:findAllStrategy.getList()){
			System.out.println(strategy.getThemes());
		}
		model.addAttribute("findAllStrategy", findAllStrategy);
		return "/strategy.jsp";
	}
	/**
	 * 查询动态（按地址分类）
	 */
	@RequestMapping(value="strategyclassification")
	public String classificationStrategy(@RequestParam("address") String address,Model model,HttpServletRequest request){
		System.out.println(address);
		int pageNum = Integer.parseInt(request.getParameter("pageNum")==null||request.getParameter("pageNum").equals("")?"1":request.getParameter("pageNum"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize")==null||request.getParameter("pageSize").equals("")?"8":request.getParameter("pageSize"));
		Page<Strategy> findAllStrategy = serviceImpl.classificationStrategy(pageNum, pageSize, address);
		model.addAttribute("findAllStrategy",findAllStrategy);
		return "/strategy.jsp";
	}
	
}
